package com.smart.seven.aop.advice.throwsadvice;

import org.springframework.aop.ThrowsAdvice;

import java.lang.reflect.Method;
import java.sql.SQLException;

/**
 * 异常增强类
 *
 * @author junrui.wang
 * @create 2018/10/10
 */
public class TransactionManager implements ThrowsAdvice {

    //定义增强逻辑
    public void afterThrowing(Method method, Object[] args, Object target, Exception e){
        System.out.println("---Exception---");
        System.out.println("method:" + method.getName());
        System.out.println("抛出异常:" + e.getMessage());
        System.out.println("回滚成功");
    }

    //方法名必须为afterThrowing，Method method, Object[] args, Object target可以选填（3个要么都有，要么都没有），最后一个参数必须是Throwable或者子类
    public void afterThrowing(RuntimeException e){
        System.out.println("---RuntimeException---");
        System.out.println("抛出异常:" + e.getMessage());
        System.out.println("回滚成功");
    }

    //可定义多个afterThrowing，Spring会自动选择最匹配的增强方法，（继承树上越接近，说明两个类越相似）
    public void afterThrowing(SQLException e){
        System.out.println("---SQLException---");
        System.out.println("抛出异常:" + e.getMessage());
        System.out.println("回滚成功");
    }

}
